package kr.saeildamil.androidstudy.ch19;

import kr.saeildamil.androiddforstudy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class BackWork extends Activity {
	TextView mResult;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_backwork);
		setProgressBarIndeterminateVisibility(false);
		
		mResult = (TextView) findViewById(R.id.ch19_backwork_resulttv);
	}
	
	public void mOnClick(View v){
		new BackWorkAsyncTask().execute(0,100);
	}
	
	class BackWorkAsyncTask extends AsyncTask<Integer, Integer, Integer>{
		boolean mQuit;
		ProgressDialog mProgress;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgress = new ProgressDialog(BackWork.this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("Now Calculating");
			mProgress.setMessage("Please Wait...");
			mProgress.setProgress(0);
			mProgress.setCancelable(false);
			mProgress.setButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					mQuit = true;
					mProgress.dismiss();
				}
			});
			mProgress.show();
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			int result=0;
			for(int i=params[0]; i<params[1]+1; i++){
				result += i;
				publishProgress(result);
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {}
				if(mQuit){
					return result;
				}
			}
			return result;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			mResult.setText(result + "");
			mProgress.dismiss();
			mQuit=false;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			mResult.setText("");
			mQuit=false;
		}
		
	} // End of class AsyncTask;
	
} // End of class BackWork;